package com.googlecode.etrade.client.ncortab;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.grid.AggregationRenderer;
import com.extjs.gxt.ui.client.widget.grid.AggregationRowConfig;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupSummaryView;
import com.extjs.gxt.ui.client.widget.grid.SummaryColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.SummaryRenderer;
import com.extjs.gxt.ui.client.widget.grid.SummaryType;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Element;
import com.googlecode.etrade.client.comum.ItemResumoFinanceiro;
import com.googlecode.etrade.client.comum.ItemResumoNegocio;
import com.googlecode.etrade.client.comum.Negocio;

public class NCorretagemForm extends LayoutContainer {

	private FormPanel fp = new FormPanel();
	FormData formData = new FormData("95%");

	@Override
	protected void onRender(Element target, int index) {
		super.onRender(target, index);

		fp.setFrame(true);
		fp.setHeading("Nota de Corretagem");
		fp.setSize(650, -1);
		fp.setButtonAlign(HorizontalAlignment.CENTER);

		configHead();
		configBody();

		add(fp);
	}

	private void configHead() {
		LayoutContainer main = new LayoutContainer();
		main.setLayout(new ColumnLayout());

		LayoutContainer col1 = new LayoutContainer();
		col1.setStyleAttribute("paddingRight", "10px");
		FormLayout layout = new FormLayout();
		layout.setLabelAlign(LabelAlign.TOP);
		col1.setLayout(layout);

		TextField<String> numero = new TextField<String>();
		numero.setFieldLabel("Número");
		numero.setAllowBlank(false);
		numero.setWidth(30);

		col1.add(numero, formData);

		LayoutContainer col2 = new LayoutContainer();
		col2.setStyleAttribute("paddingRight", "10px");
		layout = new FormLayout();
		layout.setLabelAlign(LabelAlign.TOP);
		col2.setLayout(layout);

		DateField dtPregao = new DateField();
		dtPregao.setFieldLabel("Data do Pregão");

		col2.add(dtPregao, formData);

		LayoutContainer col3 = new LayoutContainer();
		col3.setStyleAttribute("paddingRight", "10px");
		layout = new FormLayout();
		layout.setLabelAlign(LabelAlign.TOP);
		col3.setLayout(layout);

		DateField liquidacao = new DateField();
		liquidacao.setFieldLabel("Liquidação");

		col3.add(liquidacao, formData);

		main.add(col1, new ColumnData(.4));
		main.add(col2, new ColumnData(.4));
		main.add(col3, new ColumnData(.4));

		fp.add(main);
	}

	private void configBody() {

		final ListStore<Negocio> store = new ListStore<Negocio>();

		LayoutContainer botoes = new LayoutContainer();
		botoes.setLayout(new ColumnLayout());

		LayoutContainer col1 = new LayoutContainer();
		col1.setStyleAttribute("paddingRight", "10px");

		LayoutContainer col2 = new LayoutContainer();
		col2.setStyleAttribute("paddingRight", "10px");

		SelectionListener<ButtonEvent> btnEvt = new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				String id = ce.getButton().getId();
				if (id.equalsIgnoreCase("btnNegocio")) {
					store.add(getNegocio());
				} else if (id.equalsIgnoreCase("saveNegocio")) {
					store.commitChanges();
				}
			}
		};

		Button nNegocio = new Button("Novo Negócio", btnEvt);
		nNegocio.setId("btnNegocio");
		nNegocio.setIconStyle("icon-new");

		col1.add(nNegocio);

		Button saveNegocio = new Button("Salvar", btnEvt);
		saveNegocio.setId("saveNegocio");

		col2.add(saveNegocio);

		botoes.add(col1, new ColumnData(.4));
		botoes.add(col2, new ColumnData(.4));

		fp.add(botoes);

		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();

		ColumnConfig column = new ColumnConfig("mercado", "Mercado", 130);

		final SimpleComboBox<String> combo = new SimpleComboBox<String>();
		combo.setForceSelection(true);
		combo.setTriggerAction(TriggerAction.ALL);
		// TODO Transformar em enumeração
		combo.add("A Vista");
		combo.add("A Termo");

		column.setEditor(getCellEditor(combo));
		configs.add(column);

		column = new ColumnConfig("cv", "C/V", 30);

		final SimpleComboBox<String> cmbCv = new SimpleComboBox<String>();
		cmbCv.setForceSelection(true);
		cmbCv.setTriggerAction(TriggerAction.ALL);
		cmbCv.add("C");
		cmbCv.add("V");

		column.setEditor(getCellEditor(cmbCv));
		configs.add(column);

		column = new ColumnConfig("titulo", "Título", 100);

		final SimpleComboBox<String> cmbTit = new SimpleComboBox<String>();
		cmbTit.setForceSelection(true);
		cmbTit.setTriggerAction(TriggerAction.ALL);
		cmbTit.add("Abyara ON");
		cmbTit.add("LLXL Log ON");

		column.setEditor(getCellEditor(cmbTit));
		configs.add(column);

		column = new ColumnConfig("obs", "Obs.", 50);

		TextField<String> txtObs = new TextField<String>();
		txtObs.setAllowBlank(false);

		column.setEditor(new CellEditor(txtObs));
		configs.add(column);

		column = new ColumnConfig("quantidade", "Quantidade", 90);

		TextField<String> txtQtd = new TextField<String>();
		txtQtd.setAllowBlank(false);

		column.setEditor(new CellEditor(txtQtd));
		column.setAlignment(HorizontalAlignment.RIGHT);
		configs.add(column);

		column = new ColumnConfig("preco", "Preço", 50);

		TextField<String> txtPreco = new TextField<String>();
		txtPreco.setAllowBlank(false);

		column.setEditor(new CellEditor(txtPreco));
		column.setAlignment(HorizontalAlignment.RIGHT);
		column.setNumberFormat(NumberFormat.getDecimalFormat());
		configs.add(column);

		column = new ColumnConfig("valor", "Valor", 50);

		TextField<String> txtValor = new TextField<String>();
		txtValor.setAllowBlank(false);

		column.setEditor(new CellEditor(txtValor));
		column.setAlignment(HorizontalAlignment.RIGHT);
		column.setNumberFormat(NumberFormat.getDecimalFormat());
		configs.add(column);

		column = new ColumnConfig("dc", "D/C", 50);

		final SimpleComboBox<String> cmbDC = new SimpleComboBox<String>();
		cmbDC.setForceSelection(true);
		cmbDC.setTriggerAction(TriggerAction.ALL);
		cmbDC.add("D");
		cmbDC.add("C");

		column.setEditor(getCellEditor(cmbDC));
		configs.add(column);

		ColumnModel cm = new ColumnModel(configs);

		EditorGrid<Negocio> grid = new EditorGrid<Negocio>(store, cm);
		grid.setBorders(true);
		grid.setHeight(120);

		// fp.add(grid);

		// Detalhes

		LayoutContainer detalhes = new LayoutContainer();
		detalhes.setLayout(new ColumnLayout());
		// detalhes.setStyleAttribute("paddingTop", "10px");

		LayoutContainer resumoNegocios = new LayoutContainer();
		resumoNegocios.setStyleAttribute("paddingRight", "10px");

		FormPanel frmResumo = new FormPanel();
		frmResumo.setHeading("Resumo dos Negócios");
		frmResumo.setFrame(true);
		frmResumo.setPadding(0);
		frmResumo.setWidth(250);

		configs = new ArrayList<ColumnConfig>();

		column = new ColumnConfig("nome", "Nome", 164);
		configs.add(column);

		column = new ColumnConfig("valor", "Valor", 50);
		column.setAlignment(HorizontalAlignment.RIGHT);
		column.setNumberFormat(NumberFormat.getDecimalFormat());
		configs.add(column);

		NotaCorretagem notaCorretagem = new NotaCorretagem();

		final ListStore<ItemResumoNegocio> storeResumoNeg = new ListStore<ItemResumoNegocio>();

		storeResumoNeg.add(notaCorretagem.getResumoDoNegocio());

		cm = new ColumnModel(configs);

		final NumberFormat number = NumberFormat.getFormat("0.00");
		AggregationRowConfig<ItemResumoNegocio> total = new AggregationRowConfig<ItemResumoNegocio>();
		total.setHtml("nome", "Valor das operações");
		total.setSummaryFormat("valor", number);
		total.setSummaryType("valor", SummaryType.SUM);
		total.setRenderer("valor",
				new AggregationRenderer<ItemResumoNegocio>() {
					public Object render(Number value, int colIndex,
							Grid<ItemResumoNegocio> grid,
							ListStore<ItemResumoNegocio> store) {
						// you can return html here
						return number.format(value.doubleValue());
					}
				});

		cm.addAggregationRow(total);

		Grid<ItemResumoNegocio> gridResumo = new Grid<ItemResumoNegocio>(
				storeResumoNeg, cm);
		gridResumo.setBorders(true);
		gridResumo.setHeight(400);

		frmResumo.add(gridResumo);

		resumoNegocios.add(frmResumo);

		// Resumo Financeiro

		LayoutContainer resumoFinanceiro = new LayoutContainer();

		FormPanel frmFinanceiro = new FormPanel();
		frmFinanceiro.setHeading("Resumo Financeiro");
		frmFinanceiro.setFrame(true);
		frmFinanceiro.setPadding(0);
		frmFinanceiro.setWidth(250);

		configs = new ArrayList<ColumnConfig>();

		SummaryColumnConfig<Double> agregColumn = new SummaryColumnConfig<Double>(
				"agreg", "", 60);
		configs.add(agregColumn);

		SummaryColumnConfig<Integer> nomeColumn = new SummaryColumnConfig<Integer>(
				"nome", "Nome", 164);
		configs.add(nomeColumn);
		nomeColumn.setSummaryType(SummaryType.COUNT);
		nomeColumn.setSummaryRenderer(new SummaryRenderer() {
			public String render(Number value, Map<String, Number> data) {
				return "Total";
			}
		});

		SummaryColumnConfig<Double> valColumn = new SummaryColumnConfig<Double>(
				"valor", "Valor", 50);
		valColumn.setSummaryFormat(NumberFormat.getDecimalFormat());
		valColumn.setSummaryType(SummaryType.SUM);
		valColumn.setSummaryRenderer(new SummaryRenderer() {
			public String render(Number value, Map<String, Number> data) {
				return "R$ " + value.intValue();
			}
		});

		configs.add(valColumn);

		SummaryColumnConfig<Double> dcColumn = new SummaryColumnConfig<Double>(
				"dc", "D/C.", 50);
		dcColumn.setAlignment(HorizontalAlignment.RIGHT);
		configs.add(dcColumn);

		final GroupingStore<ItemResumoFinanceiro> storeFin = new GroupingStore<ItemResumoFinanceiro>();

		storeFin.add(notaCorretagem.getResumoFinanceiro());
		storeFin.groupBy("agreg");

		final ColumnModel cmFin = new ColumnModel(configs);

		GroupSummaryView view = new GroupSummaryView();
		view.setShowGroupedColumn(false);
		view.setForceFit(true);
		view.setGroupRenderer(new GridGroupRenderer() {
			public String render(GroupColumnData data) {
				String l = data.models.size() == 1 ? "Item" : "Items";
				return data.group + " (" + data.models.size() + " " + l + ")";
			}
		});

		EditorGrid<ItemResumoFinanceiro> gridFin = new EditorGrid<ItemResumoFinanceiro>(
				storeFin, cmFin);
		gridFin.setView(view);
		gridFin.getView().setShowDirtyCells(false);
		gridFin.setBorders(true);
		gridFin.setHeight(600);

		frmFinanceiro.add(gridFin);

		resumoFinanceiro.add(frmFinanceiro);

		detalhes.add(resumoNegocios, new ColumnData(.4));
		detalhes.add(resumoFinanceiro, new ColumnData(.4));

		fp.add(detalhes);

	}

	private CellEditor getCellEditor(final SimpleComboBox<String> cmb) {

		CellEditor editor = new CellEditor(cmb) {
			@Override
			public Object preProcessValue(Object value) {
				if (value == null) {
					return value;
				}
				return cmb.findModel(value.toString());
			}

			@Override
			public Object postProcessValue(Object value) {
				if (value == null) {
					return value;
				}
				return ((ModelData) value).get("value");
			}
		};
		return editor;
	}

	private Negocio getNegocio() {
		Negocio negocio;
		negocio = new Negocio("A Vista", "C", "Título", "H", 0, 0.0, 0.0, "D");

		return negocio;
	}

}